#import "TrayMenu.h"
#import "LoginItem.h"


@implementation TrayMenu

// Constructor
- (TrayMenu *) init {
	self = [super init];
	
	// Init dict
	_menuMap = [[NSMutableDictionary alloc] init];
	_registeredItems = [[NSMutableDictionary alloc] init];
	_sharedWorkspace = [NSWorkspace sharedWorkspace];
	_initalNumberOfItems = 0;
	
	return self;
}

// Register notifications
- (void) registerNotifications {
	[[_sharedWorkspace notificationCenter]	addObserver:self 
											selector:@selector(mountNotificationOccured:) 
											name:NSWorkspaceDidMountNotification 
											object:nil];
	
	[[_sharedWorkspace notificationCenter]	addObserver:self 
											selector:@selector(unmountNotificationOccured:)
											name:NSWorkspaceDidUnmountNotification 
											object:nil];	
}

// Notification method for MOUNT
- (void) mountNotificationOccured:(NSNotification *)notification {
	NSString *itemPath = [[notification userInfo] objectForKey:@"NSDevicePath"];
	if([_registeredItems objectForKey:itemPath] != nil)
		NSLog(@"Path already registered? %@", itemPath);
	
	[self addItemFromPath:itemPath];
}

// Notification method for UNMOUNT
- (void) unmountNotificationOccured:(NSNotification *)notification {
	NSString *itemPath = [[notification userInfo] objectForKey:@"NSDevicePath"];
	NSString *mapKey = [_registeredItems objectForKey:itemPath];
	
	if(mapKey == nil)
		NSLog(@"Mount not registered? %@", itemPath);
	
	NSDictionary *itemInfo = [_menuMap objectForKey:mapKey];
	
	// Removal
	[_menu removeItem:[itemInfo objectForKey:@"menuItem"]];
	[_menuMap removeObjectForKey:mapKey];
	[_registeredItems removeObjectForKey:itemPath];
}

// Terminate app
- (void) actionQuit:(id)sender {
	[NSApp terminate:sender];
}

// Toggle wheather App starts at login or not
- (void) toggleStartAtLogin:(id)sender {
	BOOL state = [LoginItem willStartAtLogin:[self appURL]];

	if(state)
		state = NO;
	else
		state = YES;
				  
				  
    [LoginItem setStartAtLogin:[self appURL] enabled:state];
	NSMenuItem *menuItem = sender;

	// Set check mark
	if(state)
		[menuItem setState:NSOnState];
	else
		[menuItem setState:NSOffState];				  
	
}

// Open Finder for given URL
- (void) openMountInFinder:(id)sender {
	NSMenuItem *menuItem = sender;
	NSDictionary *itemDict = [_menuMap objectForKey:[menuItem description]];
	
	if(itemDict == nil)
		return;
	
	[_sharedWorkspace openURL:[itemDict objectForKey:@"url"]];
}

// Add a menu item
- (void) addItemFromPath:(NSString *) itemPath {
	NSFileManager *fileManager = [[NSFileManager alloc] init];

	// Extract Info
	NSURL *fileURL = [NSURL fileURLWithPath: itemPath];
	NSImage  *icon = [_sharedWorkspace iconForFile:[fileURL path]];
	NSString *displayName = [fileManager displayNameAtPath:itemPath];
	
	// The index the new item is stored
	int insertIndex = [_menu numberOfItems] - _initalNumberOfItems;
	
	// Add menu entry
	NSMenuItem *menuItem = [_menu	insertItemWithTitle:displayName
									action:@selector(openMountInFinder:)
									keyEquivalent:@""
									atIndex:insertIndex];
	
	// Configure item
	[menuItem setImage:icon];
	[menuItem setTarget:self];
	
	// Create Description Array
	NSArray *itemDictKeys = [NSArray arrayWithObjects:@"menuItem", @"path", @"displayName", @"url", @"icon", nil];
	NSArray *itemDictObjects = [NSArray arrayWithObjects:menuItem, itemPath, displayName, fileURL, icon, nil];
	NSDictionary *itemDict = [NSDictionary dictionaryWithObjects:itemDictObjects forKeys:itemDictKeys];
	
	// Resize the Icon
	[icon setSize:NSMakeSize(16.0, 16.0)];
	
	// Store information
	[_menuMap setObject:itemDict forKey:[menuItem description]];
	[_registeredItems setObject:[menuItem description] forKey:itemPath];
	
	// View
	MenuItemController *menuItemController = [[MenuItemController alloc] initWithNibName:@"MenuItemView" bundle:nil dataDictionary:itemDict];
	[menuItem setView:[menuItemController view]];
}

// First add all mounts to menu
- (void) addMountsToMenu {	
	NSArray *mountedVolumes = [_sharedWorkspace mountedLocalVolumePaths];
	for(NSString *itemPath in mountedVolumes) {
		[self addItemFromPath:itemPath];

	}
}

// Create the menu
- (void) createMenu {
	NSZone *menuZone = [NSMenu menuZone];
	NSMenuItem *menuItem;
	
	_menu = [[NSMenu allocWithZone:menuZone] init];
	
	// Add Separator
	[_menu addItem:[NSMenuItem separatorItem]];
	
	// Add Login item
	menuItem = [_menu	addItemWithTitle:NSLocalizedString(@"Enable at login",nil)
						action:@selector(toggleStartAtLogin:)
						keyEquivalent:@""];
	
	// Set check mark
	if([LoginItem willStartAtLogin:[self appURL]])
		[menuItem setState:NSOnState];
	else
		[menuItem setState:NSOffState];
		
	[menuItem setTarget:self];
	
	// Add Quit Action
	menuItem = [_menu	addItemWithTitle:NSLocalizedString(@"Quit",nil)
						action:@selector(actionQuit:)
						keyEquivalent:@"Q"];
	
	[menuItem setToolTip:NSLocalizedString(@"Quit Mounter",nil)];
	[menuItem setTarget:self];
	
	_initalNumberOfItems = [_menu numberOfItems];
	
	[self addMountsToMenu];
}

// Interface: Application komplett geladen
- (void) applicationDidFinishLaunching:(NSNotification *)notification {
	
	[self createMenu];
	
	_statusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength] retain];
	[_statusItem setMenu:_menu];
	[_statusItem setHighlightMode:YES];
	[_statusItem setToolTip:@"Mounter"];
	
	NSImage *menuBarIcon = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"mounter" ofType:@"png"]];
	
	[_statusItem setImage:menuBarIcon];
	
	[_menu release];
}

// App URL
- (NSURL *)appURL {
	return [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
}

@end